const {
  User,
  validateUser
} = require("../../model/user");

// 引入哈希加密模块
const bcrypt = require("bcrypt");

const register = async (req, res) => {
  // console.log(req.body);
  try {
    await validateUser(req.body);
  } catch (err) {
    res.send({
      code: 400,
      data: {},
      msg: err.message,
    });
  }
  // 根据用户名查询用户信息
  const user = await User.findOne({
    username: req.body.username,
  });
  if (user) {
    res.send({
      code: 400,
      data: {},
      msg: "用户名已经被占用",
    });
  } else {
    // 加密用户密码
    // 生成随机盐值
    const salt = await bcrypt.genSalt(10);
    // 加密密码
    const password = await bcrypt.hash(req.body.password, salt);
    // 替换密码
    req.body.password = password;
    // 将用户信息添加到数据库
    // console.log(req.body);
    await User.create(req.body);
    const userInfo = await User.findOne({
      username: req.body.username
    });
    res.send({
      code: 200,
      data: {
        userInfo: userInfo,
      },
      msg: "注册成功",
    });
  }
};

module.exports = register;